//
// Created by aruba on 2020/4/16.
//

#include "_FileClass.h"

//构造函数初始化
CFILE::CFILE() {
    m_fp = 0;
    memset(m_filename, 0, sizeof(m_filename));
    m_buffenable = true;
}

//带参数构造函数初始化
CFILE::CFILE(bool buffenable) {
    m_fp = 0;
    memset(m_filename, 0, sizeof(m_filename));
    m_buffenable = buffenable;
}

//打开文件
bool CFILE::Open(const char *filename, const char *mode) {
    if ((m_fp = fopen(filename, mode)) == 0) return false;

    strcpy(m_filename, filename);

    return true;
}

//fgets,读文件
bool CFILE::Fgets(char *buff, int readsize) {
    if (m_fp == 0) return false;

    if (access(m_filename, R_OK) == -1) return false;

    //初始化buff
    memset(buff, 0, sizeof(readsize));

    if (fgets(buff, readsize, m_fp) == 0) return false;

    return true;
}

//fgets,一个字节读文件
int CFILE::Fgetc() {
    if (m_fp == 0) return EOF;

    return fgetc(m_fp);
}

//写文件
void CFILE::Fprintf(const char *write) {
    if (m_fp == 0) return;

    if (access(m_filename, W_OK) == -1) return;

    fprintf(m_fp, write);

    if (m_buffenable == false) fflush(m_fp);
}

//写文件
void CFILE::Fprintf(const char *format, ...) {
    if (m_fp == 0) return;

    if (access(m_filename, W_OK) == -1) return;

    va_list va;
    va_start(va, format);

    fprintf(m_fp, format);

    va_end(va);

    if (m_buffenable == false) fflush(m_fp);
}

//一个字节写文件
void CFILE::Fputc(const int c) {
    if (m_fp == 0) return;

    fputc(c, m_fp);
    if (m_buffenable == false) fflush(m_fp);
}

//获取文件大小
long CFILE::GetFileSize() {
    if (m_fp == 0) return 0;

    if (access(m_filename, R_OK) == -1) return 0;

    //将文件指针移动到文件尾
    fseek(m_fp, 0, SEEK_END);
    long size = ftell(m_fp);

    //还原文件指针
    rewind(m_fp);
    return size;
}

//析构函数
CFILE::~CFILE() {
    fclose(m_fp);
    m_fp = 0;
    m_buffenable = true;
    memset(m_filename, 0, sizeof(m_filename));
}